package com.glwan.fixedassetapp.ui.login;


import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.glwan.fixedassetapp.MainActivity;
import com.glwan.fixedassetapp.R;
import com.glwan.fixedassetapp.utils.CommonUtil;
import com.glwan.fixedassetapp.utils.DatabaseUtil;
import com.glwan.fixedassetapp.utils.KingDeeUtil;
import com.google.gson.Gson;
import com.kingdee.bos.webapi.entity.IdentifyInfo;
import com.kingdee.bos.webapi.entity.RepoResult;
import com.kingdee.bos.webapi.sdk.K3CloudApi;

import org.apache.commons.lang.StringUtils;

import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;


public class LoginActivity extends AppCompatActivity {

    private static final String TAG = "LoginActivity";
    EditText etUsername;
    EditText etPassword;
    EditText etServerAddress;
    DatabaseUtil databaseUtil;

    private Handler handler;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        databaseUtil = DatabaseUtil.getInstance(this);
        Log.i(TAG, "初始化database");
        TextView tvTitle = findViewById(R.id.tvTitle);
        tvTitle.setText(getString(R.string.login));
        etUsername = findViewById(R.id.etUsername);
        etPassword = findViewById(R.id.etPassword);
        etServerAddress = findViewById(R.id.etServerAddress);
        Button bLogin = findViewById(R.id.bLogin);
        bLogin.setOnClickListener(view -> {
            if (StringUtils.isEmpty(etServerAddress.getText().toString())) {
                CommonUtil.toastShow(getActivity(), "地址为空", CommonUtil.ERROR, true);
                return;
            }
            if (StringUtils.isEmpty(etUsername.getText().toString()) || StringUtils.isEmpty(etPassword.getText().toString())) {
                CommonUtil.toastShow(getActivity(), "用户名或者密码为空", CommonUtil.ERROR, true);
                return;
            }

            // 启动后台线程执行网络操作
            ExecutorService executor = Executors.newSingleThreadExecutor();
            executor.submit(new Runnable() {
                @Override
                public void run() {
                    // 执行网络请求
                    RepoResult repoResult = login(etServerAddress.getText().toString(), etUsername.getText().toString(), etPassword.getText().toString());
//                    Log.i(TAG, "login: "+ new Gson().toJson(repoResult));
                    // 使用 Handler 将结果传递到主线程
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (repoResult != null && repoResult.getResponseStatus().isIsSuccess()){
                                // 登录成功
                                jumpHomePage(1);
                            }else if(repoResult==null){
                                CommonUtil.toastShow(getActivity(), "网络异常", CommonUtil.ERROR, true);
                            } else {
                                CommonUtil.toastShow(getActivity(), "用户名或者密码错误", CommonUtil.ERROR, true);
                            }
                        }
                    });
                }
            });
        });
//        Button bOfflineLogin = findViewById(R.id.bOfflineLogin);
//        bOfflineLogin.setOnClickListener(view -> {
//            jumpHomePage(0);
//        });
    }


    private RepoResult login(String url, String userName, String password) {
        IdentifyInfo identifyInfo = KingDeeUtil.getIdentifyInfo();
        identifyInfo.setUserName(userName);
        identifyInfo.setServerUrl(url);
        identifyInfo.setAppSecret(password);
        try {

            K3CloudApi api = new K3CloudApi(identifyInfo);
            return api.CheckAuthInfo();
        } catch (Exception e) {
            Log.e(TAG, "登陆异常", e);
            return null;
        }
    }


    private void jumpHomePage(int menuType) {
        if (!canUse()) {
            return;
        }
        CommonUtil.openProgressDialog(getActivity(), getString(R.string.loading));
        Map<String, Object> map = new HashMap<>();
        //菜单类型: 1-在线版本, 0-离线版本
        map.put("menuType", menuType);
        CommonUtil.startActivity(getActivity(), MainActivity.class, map, true);
        CommonUtil.cancelProgressDialog(getActivity());
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            return CommonUtil.exitApp(this);
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 许可证
     *
     * @return
     */
    private boolean canUse() {
        LocalDate canUseDate = LocalDate.of(2024, 10, 30);
        LocalDate now = LocalDate.now();
        if (now.isAfter(canUseDate)) {
            CommonUtil.toastShow(getActivity(), "许可已过期", CommonUtil.ERROR, true);
            return false;
        }
        return true;
    }

    private Activity getActivity() {
        return LoginActivity.this;
    }


}
